package com.charles.seckillAuth.controller;

import com.charles.seckillAuth.form.LoginForm;
import com.charles.seckillAuth.form.RegisterForm;
import com.charles.seckillAuth.service.SysLoginService;
import com.charles.seckillAuth.service.SysRegisterService;
import com.charles.seckillData.feignService.RemoteLogService;
import com.charles.seckillData.model.UserLogin;
import com.charles.seckillComponentCommon.constants.RoleConstants;
import com.charles.seckillComponentCommon.domain.R;
import com.charles.seckillComponentSecurity.service.TokenService;
import com.charles.seckillComponentSecurity.utils.ThreadUtil;
import com.charles.seckillComponentSecurity.utils.auth.AuthVerifyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Charles-H
 * 
 * 认证控制层
 */
@RestController
public class TokenController {

    @Resource
    private SysLoginService sysLoginService;

    @Resource
    private SysRegisterService sysRegisterService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RemoteLogService remoteLogService;

    /**
     * 登录认证
     */
    @PostMapping("login")
    public R<?> login(@RequestBody LoginForm loginForm) {
        UserLogin user = sysLoginService.login(loginForm.getUserCard(), loginForm.getPassword());
        return R.success(tokenService.createToken(user));
    }

    /**
     * 后台管理系统登录认证
     */
    @PostMapping("/admin/login")
    public R<?> adminLogin(@RequestBody LoginForm loginForm) {
        UserLogin user = sysLoginService.loginAdmin(loginForm.getUserCard(), loginForm.getPassword());
        return R.success(tokenService.createToken(user));
    }

    /**
     * 注册认证
     */
    @PostMapping("register")
    public R<?> register(@RequestBody RegisterForm registerForm) {
        sysRegisterService.register(registerForm.getUsername(), registerForm.getUserCard(), registerForm.getPassword(), registerForm.getAge(), registerForm.getSex());
        return R.success();
    }

    /**
     * 退出登录
     */
    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        String token = ThreadUtil.getToken(request);
        // 远程调用日志
        remoteLogService.logoutRecord(AuthVerifyUtil.getUserLogin(token), RoleConstants.INNER);

        if (token != null && !token.isEmpty()) {
            AuthVerifyUtil.logOutByToken(token);
        }
        return R.success();
    }

}
